/*
 * @FilePath: /fxfzywpt/src/utils/map.js
 * @Description:
 */
/**
 * 字符串转geojson
 * @param {Array} data
 */
export function convertToGeoJSON(data) {
  const geojson = {
    type: 'FeatureCollection',
    features: [],
  };
  data.forEach((item) => {
    const feature = parseGeometryString(item);
    geojson.features.push(feature);
  });

  return geojson;
}
function parseGeometryString(data) {
  let inputString = data.geom;
  // 检查几何类型
  var geomType;
  if (inputString.includes('MULTIPOLYGON')) {
    console.log('2');
    geomType = 'MultiPolygon';
  } else if (inputString.includes('POLYGON')) {
    console.log('1');
    geomType = 'Polygon';
  } else {
    throw new Error('Unrecognized geometry type');
  }

  // 提取坐标点
  var coordinates = [];
  var coordinatesStr;
  console.log('geomType--', geomType);
  if (geomType == 'Polygon') {
    coordinatesStr = inputString.split('((')[1].split('))')[0];
  } else if (geomType == 'MultiPolygon') {
    console.log('inputString---', inputString);
    coordinatesStr = inputString.split('(((')[1].split(')))')[0];
  }
  if (geomType == 'Polygon') {
    var rings = coordinatesStr.split('),(');
    rings.forEach(function (ringStr) {
      var ringCoordinates = ringStr.split(',').map(function (coordPairStr) {
        var coords = coordPairStr.trim().split(' ');
        var lon = parseFloat(coords[0]);
        var lat = parseFloat(coords[1]);
        if (isNaN(lon) || isNaN(lat)) {
          throw new Error('Invalid coordinates: ' + coordPairStr);
        }
        return [lon, lat];
      });
      coordinates.push(ringCoordinates);
    });
  } else {
    coordinates = [
      coordinatesStr.split(',').map((coordStr) => {
        const [lon, lat] = coordStr.trim().split(' ');
        return [parseFloat(lon), parseFloat(lat)];
      }),
    ];
  }
  console.log('coordinates---', coordinates);
  // 构建GeoJSON对象
  var geometry;
  if (geomType === 'Polygon') {
    geometry = {
      type: 'Polygon',
      coordinates: coordinates,
    };
  } else {
    geometry = {
      type: 'MultiPolygon',
      coordinates: [coordinates],
    };
  }
  var geojson = {
    type: 'Feature',
    geometry: geometry,
    properties: {
      type: 2,
      id: data.id,
      county: data.county,
      countyCode: data.countyCode,
      area: parseFloat(data.area),
      intensity: data.intensity,
    },
  };

  return geojson;
}
